<?php
// +----------------------------------------------------------------------
// | ZGUAN [ 致力于帮助更多的中小企业物联网转型 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2024 https://www.zguan.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ZGUAN 并不是自由软件，未经许可不能去掉ZGUAN 相关版权
// +----------------------------------------------------------------------
// | Author: ZGUAN Team <admin@zguan.cn>  0769-82282996  15899929162
// +----------------------------------------------------------------------
namespace app\controller\property\auth;

use think\App;
use app\controller\property\Base;
use app\validate\property\auth\AuthRoleValidate;
use app\common\repositories\property\basic\PropertyBasicRepository;
use app\common\repositories\property\auth\PropertyAuthRoleRepository;
use app\common\repositories\property\auth\PropertyAuthRuleRepository;

class PropertyAuthRole extends Base
{
    protected $repository;

    public function __construct(App $app, PropertyAuthRoleRepository $repository)
    {
        parent::__construct($app);

        $this->repository = $repository;
    }


    protected function commonParams()
    {
        /** @var PropertyBasicRepository $propertyBasicRepository */
        $propertyBasicRepository = app()->make(PropertyBasicRepository::class);
        $propertyData = $propertyBasicRepository->getUserAllPropertyList($this->request->userId);
        $this->assign([
            'propertyData' => $propertyData,
        ]);
    }

    /**
     * 角色列表
     * @return string|\think\response\Json
     * @throws \Exception
     *
     * @author Amos
     * 2024-01-16 22:20
     */
    public function list()
    {
        if ($this->request->isAjax()) {
            $where = $this->request->param([
                'property_id' => '',
                'keywords' => '',
            ]);
            [$page, $limit] = $this->getPage();
            $res = $this->repository->getPropertyList($where, $page, $limit, $this->request->userId);
            return json()->data(['code' => 0, 'data' => $res['list'], 'count' => $res['count']]);
        } else {
            $this->commonParams();
            return $this->fetch('auth/role/list', [
                'addAuth' => property_auth('propertyAuthRoleAdd'),
                'editAuth' => property_auth('propertyAuthRoleEdit'),
                'delAuth' => property_auth('propertyAuthRoleDel'),
                'detailAuth' => property_auth('propertyAuthRoleDetail')
            ]);
        }
    }

    /**
     * 添加角色
     * @return string|\think\response\Json|\think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     *
     * @author Amos
     * 2024-01-16 22:21
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $param = $this->request->param([
                'name' => '',
                'property_id' => '',
                'is_show' => '',
                'remark' => '',
            ]);
            validate(AuthRoleValidate::class)->scene('add')->check($param);
            if ($this->repository->propertyFieldExists($this->request->propertyId, 'name', $param['name'])) {
                return $this->error($param['name'] . ' 角色已存在');
            }
            try {
                $dataPost = $this->request->post();
                unset($dataPost['name'], $dataPost['is_show'], $dataPost['remark']);
                $param['rules'] = implode(',', $dataPost);
                $res = $this->repository->addInfo($param, $this->request->userId);
                if ($res) {
                    return $this->success('添加成功');
                } else {
                    return $this->error('添加失败');
                }
            } catch (\Exception $e) {
                exception_log('添加角色失败', $e);
                return $this->error('网络错误');
            }
        } else {
            $this->commonParams();
            /** @var propertyAuthRuleRepository $propertyAuthRuleRepository */
            $propertyAuthRuleRepository = app()->make(propertyAuthRuleRepository::class);
            $res = arr_level_sort($propertyAuthRuleRepository->getMenuList()->toArray(), 2);
            $menus = $this->generateSelectCreateAuth($res, []);
            return $this->fetch('auth/role/add', [
                'authData' => $menus
            ]);
        }
    }

    /**
     * 编辑角色
     * @return string|\think\response\Json|\think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     *
     * @author Amos
     * 2024-01-16 22:22
     */
    public function edit()
    {
        $id = (int)$this->request->param('id');
        if (!$id) {
            return $this->error('参数错误');
        }
        $info = $this->repository->get($id);
        if (!$info) {
            return $this->error('信息错误');
        }
        if ($this->request->isPost()) {
            $param = $this->request->param([
                'name' => '',
                'property_id' => '',
                'is_show' => '',
                'remark' => '',
            ]);
            validate(AuthRoleValidate::class)->scene('edit')->check($param);
            try {
                $dataPost = $this->request->post();
                unset($dataPost['name'], $dataPost['is_show'], $dataPost['remark']);
                $param['rules'] = implode(',', $dataPost);
                $res = $this->repository->editInfo($info, $param, $this->request->userId);
                if ($res) {
                    return $this->success('修改成功');
                } else {
                    return $this->error('修改失败');
                }
            } catch (\Exception $e) {
                exception_log('编辑角色失败', $e);
                return $this->error('网络错误');
            }
        } else {
            $this->commonParams();
            $propertyAuthRuleRepository = app()->make(propertyAuthRuleRepository::class);
            $res = arr_level_sort($propertyAuthRuleRepository->getMenuList()->toArray(), 2);
            $menus = $this->generateSelectCreateAuth($res, $info);
            return $this->fetch('auth/role/edit', [
                'info' => $info,
                'authData' => $menus
            ]);

        }
    }

    /**
     * 删除角色
     * @return string|\think\response\Json|\think\response\View
     *
     * @author Amos
     * 2024-01-16 22:22
     */
    public function del()
    {
        $ids = (array)$this->request->param('ids');
        try {
            $data = $this->repository->batchDelete($ids, $this->request->userId);
            if ($data) {
                return $this->success('删除成功');
            } else {
                return $this->error('删除失败');
            }
        } catch (\Exception $e) {
            exception_log('删除角色失败', $e);
            return $this->error('网络错误');
        }
    }

    /**
     * 角色详情
     * @return string|\think\response\Json|\think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     *
     * @author Amos
     * 2024-06-29 14:54
     */
    public function detail()
    {
        $id = (int)$this->request->param('id');
        if ($id <= 0) {
            return $this->error('参数错误');
        }
        $info = $this->repository->get($id);
        if ($info['id'] <= 0) {
            return $this->error('信息不存在');
        }
        return $this->fetch('auth/role/detail', [
            'info' => $info,
        ]);
    }


    /**
     *
     * @param $rules
     * @param $ppUserInfo
     * @return array
     *
     * @author Amos
     * 2024-01-17 22:01
     */
    protected function generateSelectCreateAuth($rules, $ppUserInfo)
    {
        $userRules = array_filter(explode(',', $ppUserInfo['rules'] ?? ''));
        $arr = [];
        foreach ($rules as $k => $v) {
            $arr2 = [
                'title' => $v['name'],
                'id' => $v['id'],
                'checked' => in_array($v['id'], $userRules)
            ];
            if (isset($v[$v['id']]) && $v[$v['id']]) {
                $arr2['children'] = $this->generateSelectCreateAuth($v[$v['id']], $ppUserInfo);
                $num2 = 0;
                foreach ($arr2['children'] as $k2 => $v2) {
                    if ($v2['checked']) {
                        $num2++;
                    }
                }
                if ($num2 == count($v[$v['id']])) {
                    $arr2['checked'] = true;
                } else {
                    $arr2['checked'] = false;
                }
            }
            $arr[] = $arr2;
        }
        return $arr;
    }

}